package com.example.data;

import com.example.bean.Property;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class ConfigDataHandler {
    @Resource
    JdbcTemplate jdbcTemplate;

    public List<Property> find(String application, String profile, String label) {
        String sql = "select `key`, `value` from codeforfun_property where 1=1";
        List<Object> parameter = new ArrayList<>();
        if (!ObjectUtils.isEmpty(application)) {
            sql += " and application = ?";
            parameter.add(application);
        }
        if (!ObjectUtils.isEmpty(profile)) {
            sql += " and ( profile is null or profile = ''";
            String[] profileArray = StringUtils.commaDelimitedListToStringArray(profile);
            if (!ObjectUtils.isEmpty(profileArray)) {
                if (profileArray.length == 1) {
                    sql += " or profile = ?";
                    parameter.add(profileArray[0]);
                } else {
                    sql += " or profile in (?)";
                    parameter.add(profileArray);
                }
            }
            sql += " )";
        }
        if (!ObjectUtils.isEmpty(label)) {
            sql += " and ( label is null or label = ''";
            String[] labelArray = StringUtils.commaDelimitedListToStringArray(label);
            if (!ObjectUtils.isEmpty(labelArray)) {
                if (labelArray.length == 1) {
                    sql += " or label = ?";
                    parameter.add(labelArray[0]);
                } else {
                    sql += " or label in (?)";
                    parameter.add(labelArray);
                }
            }
            sql += " )";
        }
        return jdbcTemplate.query(sql,
                (rs, rowNum) -> new Property(rs.getString("key"), rs.getString("value")),
                parameter.toArray());
    }
}
